<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="连接名|数据库名|JDBC"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            :disabled="ids.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="dbSourceList"
        highlight-current-row
        border
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="连接名称" prop="name" width="150" />
        <el-table-column label="数据库名" prop="dbName" width="120" />
        <el-table-column label="账户名称" prop="userName" width="120" />
        <el-table-column label="JDBC地址" prop="jdbcUrl" min-width="100" />
        <el-table-column label="创建日期" prop="createTime" align="center" width="180" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="连接名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入连接名称" />
        </el-form-item>
        <el-form-item label="数据库名" prop="dbName">
          <el-input v-model="formData.dbName" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="账户名称" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="账户密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入账户密码" />
        </el-form-item>
        <el-form-item label="JDBC地址" prop="jdbcUrl">
          <el-input v-model="formData.jdbcUrl" placeholder="请输入完整连接地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DbSourceAPI, {
  DbSourceForm,
  DbSourcePageQuery,
  DbSourcePageVO,
} from "@/api/mysql/dbsource.api";

defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Source",
  inheritAttrs: false,
});

const queryFormRef = ref();
const roleFormRef = ref();
const permTreeRef = ref();
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

// 查询表单
const queryParams = reactive<DbSourcePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const dbSourceList = ref<DbSourcePageVO[]>();

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 数据表单
const formData = reactive<DbSourceForm>({
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入连接名称", trigger: "blur" }],
  dbName: [{ required: true, message: "请输入数据库名", trigger: "blur" }],
  userName: [{ required: true, message: "请输入账户名称", trigger: "blur" }],
  password: [{ required: true, message: "请输入账户密码", trigger: "blur" }],
  jdbcUrl: [{ required: true, message: "请输入完整连接地址", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

const permKeywords = ref("");

// 获取数据
function fetchData() {
  loading.value = true;
  DbSourceAPI.getPage(queryParams)
    .then((data) => {
      dbSourceList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开弹窗
function handleOpenDialog(roleId?: string) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改数据源";
    DbSourceAPI.getFormData(roleId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增数据源";
  }
}

// 提交表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        DbSourceAPI.update(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DbSourceAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 删除数据
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DbSourceAPI.deleteByIds(roleIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 权限筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

// 数据挂载
onMounted(() => {
  handleQuery();
});
</script>
